<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/28
 * Time: 15:06
 */

namespace common\components;


use common\assets\AppAsset;

class StaticAssetsComponent
{
    const TYPE_CSS = 'css';

    const TYPE_JS = 'js';

    /**
     * 载入应用文件
     * @param $type
     * @param $path
     * @param string $depend
     * @param array $option
     */
    public static function includeAppAsset($type, $path, $depend='', array $option=[])
    {
        $release_version = defined("RELEASE_VERSION") ? RELEASE_VERSION : time();

        #加入版本号
        $path = $path . '?version=' . $release_version;

        empty($depend) && $depend = AppAsset::class;

        $option = array_merge($option, [
            'depends'=>$depend
        ]);

        if ( $type == self::TYPE_CSS )
        {
           return \Yii::$app->view->registerCssFile($path, $option);
        }

        return \Yii::$app->view->registerJsFile($path, $option);
    }

    public static function includeAppJs($path, $depend='', array $option=[])
    {
        self::includeAppAsset(self::TYPE_JS, $path, $depend, $option);
    }

    public static function includeAppCss($path, $depend='', array $option=[])
    {
        self::includeAppAsset(self::TYPE_CSS, $path, $depend, $option);
    }

    /**
     * 载入static应用下的资源文件
     * @param $type
     * @param $path
     * @param string $depend
     * @param array $option
     */
    public static function includeStaticAsset($type, $path, $depend='', array $option=[])
    {
        $release_version = defined("RELEASE_VERSION") ? RELEASE_VERSION : "20150731141600";

        if (stripos($path, "?") !== false)
        {
            $path = $path . "&ver={$release_version}";
        }
        else
        {
            $path = $path . "?ver={$release_version}";
        }

        empty($depend) && $depend = AppAsset::class;

        $option = array_merge($option, [
            'depends'=>$depend
        ]);

        if ( $type == self::TYPE_CSS )
        {
            return \Yii::$app->view->registerCssFile(
                GlobalUrlComponent::buildStaticUrl($path),
                $option
            );
        }

        return \Yii::$app->view->registerJsFile(
            GlobalUrlComponent::buildStaticUrl($path),
            $option
        );
    }

    public static function includeStaticJs($path, $depend='', array $option=[])
    {
        self::includeStaticAsset(self::TYPE_JS, $path, $depend, $option);
    }

    public static function includeStaticCss($path, $depend='', array $option=[])
    {
        self::includeStaticAsset(self::TYPE_CSS, $path, $depend, $option);
    }
}